﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using DevExpress.Web.ASPxUploadControl;

namespace ElingOA6_Admin_DSJCJ.Common
{
    public class FileUpload
    {

        /// <summary>
        /// 上传文件返回新文件名称
        /// </summary>
        /// <param name="fu"></param>
        /// <param name="url">文件保存文件夹路径</param>
        /// <param name="ext">文件允许后缀名集合 如 .jpg.gif</param>
        /// <param name="maxSize">文件可上传最大大小</param>
        /// <returns></returns>
        public static string UploadFile(UploadedFile fu, string url, string ext, int maxSize = 10*1024*1024)
        {

            if (fu.ContentLength <= 0)
            {
                return "1";//文件内容为空
            }

            //获取文件类型、大小、名称

            //string type = fu.ContentType;
            int size = fu.ContentLength;
            string factFileName = Path.GetFileNameWithoutExtension(fu.FileName);
            //获取文件的扩展名
            string extension = Path.GetExtension(fu.FileName).ToLower();

            if (ext != string.Empty)
            {
                if (ext.IndexOf(extension) == -1)
                {
                    return "2";//上传类型错误
                }
            }

            if (size > maxSize)
            {
                return "3";//超出大小
            }


            //改变文件名称
            string strnewFileNmae = GenerateUtil.GenerateStringId() + "_" + factFileName;
            //判断保存文件夹是否存在
            GenerateUtil.Addfolder(url);
            string fullpath = HttpContext.Current.Server.MapPath(url) + "/" + strnewFileNmae + extension;

            //判断是否存在相同的文件
            if (File.Exists(fullpath) == true)
            {
                return "4";//文件已存在

            }
            //上传文件到硬盘
            fu.SaveAs(fullpath);
            return strnewFileNmae + extension;//文件名称
        }


        /// <summary>
        /// 生成缩略图(返回缩略图二进制值)
        /// </summary>
        /// <param name="imgPath">原图片相对路径</param>
        /// <param name="sytImgPath">缩略图保存相对路径</param>
        /// <param name="ImgWidth">缩略图宽</param>
        /// <param name="ImgHeight">缩略图高</param>
        /// <param name="mode">生成缩略图形式</param>
        public static byte[] setImgByPath(string imgPath, string sytImgPath, int ImgWidth, int ImgHeight, int mode)
        {

            imgPath = HttpContext.Current.Server.MapPath(imgPath);

            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(imgPath);

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case 1://按比例

                    double dow = double.Parse(ow.ToString());
                    double doh = double.Parse(oh.ToString());
                    double imgW = double.Parse(ImgWidth.ToString());
                    double imgH = double.Parse(ImgHeight.ToString());
                    double bl = 0;
                    if (ImgWidth == 0 || ImgHeight == 0)
                    {
                        bl = dow / doh;
                    }
                    else
                    {
                        bl = Math.Max(dow / doh, imgW / imgH);
                    }
                    imgW = imgW * bl;
                    imgH = imgH * bl;

                    string strw = imgW.ToString();
                    string strh = imgH.ToString();
                    if (strw.IndexOf(".") != -1)
                    {
                        ImgWidth = Int32.Parse(strw.Substring(0, strw.IndexOf(".")));
                    }
                    else
                    {
                        ImgWidth = Int32.Parse(strw);
                    }

                    if (strh.IndexOf(".") != -1)
                    {
                        ImgHeight = Int32.Parse(strh.Substring(0, strh.IndexOf(".")));
                    }
                    else
                    {
                        ImgHeight = Int32.Parse(strh);
                    }

                    break;
                case 2://指定高宽缩放（可能变形）                      
                    break;
                default:
                    break;
            }



            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(ImgWidth, ImgHeight);


            //新建一个画板

            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充

            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, ImgWidth, ImgHeight),
            new System.Drawing.Rectangle(x, y, ow, oh),
            System.Drawing.GraphicsUnit.Pixel);
            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(HttpContext.Current.Server.MapPath(sytImgPath), System.Drawing.Imaging.ImageFormat.Jpeg);
                //获取二进制
                MemoryStream ms = new MemoryStream();
                bitmap.Save(ms, ImageFormat.Jpeg);
                byte[] buffer = ms.ToArray();
                ms.Close();
                return buffer;
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }

        }


        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="imgPath">原图片相对路径</param>
        /// <param name="sytImgPath">缩略图保存相对路径</param>
        /// <param name="ImgWidth">缩略图宽</param>
        /// <param name="ImgHeight">缩略图高</param>
        /// <param name="mode">生成缩略图形式</param>
        public static void setImg(string imgPath, string sytImgPath, int ImgWidth, int ImgHeight, int mode)
        {

            imgPath = HttpContext.Current.Server.MapPath(imgPath);

            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(imgPath);

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case 1://按比例

                    double dow = double.Parse(ow.ToString());
                    double doh = double.Parse(oh.ToString());
                    double imgW = double.Parse(ImgWidth.ToString());
                    double imgH = double.Parse(ImgHeight.ToString());
                    double bl = 0;
                    if (ImgWidth == 0 || ImgHeight == 0)
                    {
                        bl = dow / doh;
                    }
                    else
                    {
                        bl = Math.Max(dow / doh, imgW / imgH);
                    }
                    imgW = imgW * bl;
                    imgH = imgH * bl;

                    string strw = imgW.ToString();
                    string strh = imgH.ToString();
                    if (strw.IndexOf(".") != -1)
                    {
                        ImgWidth = Int32.Parse(strw.Substring(0, strw.IndexOf(".")));
                    }
                    else
                    {
                        ImgWidth = Int32.Parse(strw);
                    }

                    if (strh.IndexOf(".") != -1)
                    {
                        ImgHeight = Int32.Parse(strh.Substring(0, strh.IndexOf(".")));
                    }
                    else
                    {
                        ImgHeight = Int32.Parse(strh);
                    }

                    break;
                case 2://指定高宽缩放（可能变形）                      
                    break;
                default:
                    break;
            }



            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(ImgWidth, ImgHeight);


            //新建一个画板

            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充

            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, ImgWidth, ImgHeight),
            new System.Drawing.Rectangle(x, y, ow, oh),
            System.Drawing.GraphicsUnit.Pixel);
            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(HttpContext.Current.Server.MapPath(sytImgPath), System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }

        }


        /// <summary>
        /// 生成缩略图(不返回任何数据)
        /// </summary>
        /// <param name="imgPath">原图片相对路径</param>
        /// <param name="sytImgPath">缩略图保存相对路径</param>
        /// <param name="ImgWidth">缩略图宽</param>
        /// <param name="ImgHeight">缩略图高</param>
        /// <param name="mode">生成缩略图形式</param>
        public static void setImg1(string imgPath, string sytImgPath, int ImgWidth, int ImgHeight, int mode)
        {

            imgPath = HttpContext.Current.Server.MapPath(imgPath);

            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(imgPath);

            int ow = originalImage.Width;
            int oh = originalImage.Height;

            int flat = 0;//标记图片是不是等比
            int xPoint = 0;//若果要补白边的话，原图像所在的x，y坐标。    
            int yPoint = 0;
            float New_Width = 0; // 新的宽度    
            float New_Height = 0; // 新的高度 

            switch (mode)
            {
                case 1://按比例

                    float dow = float.Parse(ow.ToString());
                    float doh = float.Parse(oh.ToString());
                    float imgW = float.Parse(ImgWidth.ToString());
                    float imgH = float.Parse(ImgHeight.ToString());

                    if (dow < imgW && doh < imgH)//图片的高和宽都不超出范围
                    {
                        New_Width = dow;
                        New_Height = doh;
                        xPoint = (ImgWidth - ow) / 2;
                        yPoint = (ImgHeight - oh) / 2;
                        flat = 1;
                    }
                    else if ((dow / doh) > (imgW / imgH)) //当图片太宽的时候    
                    {
                        New_Height = doh * ((float)imgW / (float)dow);
                        New_Width = (float)imgW;
                        //此时x坐标不用修改    
                        yPoint = (int)(((float)imgH - New_Height) / 2);
                        flat = 1;
                    }
                    else if ((dow / doh) == (imgW / imgH))
                    {
                        New_Width = imgW;
                        New_Height = imgH;
                    }
                    else
                    {
                        New_Width = dow * (imgH / doh);  //太高的时候   
                        New_Height = imgH;
                        //此时y坐标不用修改    
                        xPoint = (int)(((float)imgW - New_Width) / 2);
                        flat = 1;
                    }

                    //double bl = 0;
                    //if (ImgWidth == 0 || ImgHeight == 0)
                    //{
                    //    bl = dow / doh;
                    //}
                    //else
                    //{
                    //    bl = Math.Max(dow / doh, imgW / imgH);
                    //}
                    //imgW = imgW * bl;
                    //imgH = imgH * bl;

                    //string strw = imgW.ToString();
                    //string strh = imgH.ToString();
                    //if (strw.IndexOf(".") != -1)
                    //{
                    //    ImgWidth = Int32.Parse(strw.Substring(0, strw.IndexOf(".")));
                    //}
                    //else
                    //{
                    //    ImgWidth = Int32.Parse(strw);
                    //}

                    //if (strh.IndexOf(".") != -1)
                    //{
                    //    ImgHeight = Int32.Parse(strh.Substring(0, strh.IndexOf(".")));
                    //}
                    //else
                    //{
                    //    ImgHeight = Int32.Parse(strh);
                    //}

                    break;
                case 2://指定高宽缩放（可能变形）
                    New_Width = ImgWidth;
                    New_Height = ImgHeight;
                    break;
                default:
                    break;
            }



            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(ImgWidth, ImgHeight);


            //新建一个画板

            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充

            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            if (flat == 0)//指定高度缩放或等比
            {
                //g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, ImgWidth, ImgHeight),
                //           new System.Drawing.Rectangle(x, y, ow, oh),
                //           System.Drawing.GraphicsUnit.Pixel);
                g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, ImgWidth, ImgHeight),
                           new System.Drawing.Rectangle(xPoint, yPoint, ow, oh),
                           System.Drawing.GraphicsUnit.Pixel);
            }
            else
            {
                SolidBrush tbBg = new SolidBrush(Color.White);
                g.FillRectangle(tbBg, 0, 0, ImgWidth, ImgHeight); //填充为白色
                //g.DrawImage(originalImage, xPoint, yPoint, (int)New_Width, (int)New_Height);
                g.DrawImage(originalImage, new System.Drawing.Rectangle(xPoint, yPoint, (int)New_Width, (int)New_Height),
                           new System.Drawing.Rectangle(0, 0, ow, oh),
                           System.Drawing.GraphicsUnit.Pixel);

            }

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(HttpContext.Current.Server.MapPath(sytImgPath), System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }

        }



        /// <summary>
        /// 生成缩略图(返回缩略图二进制值)
        /// </summary>
        /// <param name="imgByte">原图片二进制</param>
        /// <param name="sytImgPath">缩略图保存相对路径，空则不保存到硬盘中</param>
        /// <param name="ImgWidth">缩略图宽</param>
        /// <param name="ImgHeight">缩略图高</param>
        /// <param name="mode">生成缩略图形式</param>
        public static byte[] setImgByByte(byte[] imgByte, string sytImgPath, int ImgWidth, int ImgHeight, int mode)
        {
            MemoryStream mstream = new MemoryStream(imgByte);

            System.Drawing.Image originalImage = System.Drawing.Image.FromStream(mstream);

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case 1://按比例

                    double dow = double.Parse(ow.ToString());
                    double doh = double.Parse(oh.ToString());
                    double imgW = double.Parse(ImgWidth.ToString());
                    double imgH = double.Parse(ImgHeight.ToString());
                    double bl = 0;
                    if (ImgWidth == 0 || ImgHeight == 0)
                    {
                        bl = dow / doh;
                    }
                    else
                    {
                        bl = Math.Max(dow / doh, imgW / imgH);
                    }
                    imgW = imgW * bl;
                    imgH = imgH * bl;

                    string strw = imgW.ToString();
                    string strh = imgH.ToString();
                    if (strw.IndexOf(".") != -1)
                    {
                        ImgWidth = Int32.Parse(strw.Substring(0, strw.IndexOf(".")));
                    }
                    else
                    {
                        ImgWidth = Int32.Parse(strw);
                    }

                    if (strh.IndexOf(".") != -1)
                    {
                        ImgHeight = Int32.Parse(strh.Substring(0, strh.IndexOf(".")));
                    }
                    else
                    {
                        ImgHeight = Int32.Parse(strh);
                    }

                    break;
                case 2://指定高宽缩放（可能变形）                      
                    break;
                default:
                    break;
            }



            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(ImgWidth, ImgHeight);


            //新建一个画板

            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充

            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, ImgWidth, ImgHeight),
            new System.Drawing.Rectangle(x, y, ow, oh),
            System.Drawing.GraphicsUnit.Pixel);
            try
            {
                if (sytImgPath != string.Empty)
                {
                    //以jpg格式保存缩略图
                    bitmap.Save(HttpContext.Current.Server.MapPath(sytImgPath), System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                //获取二进制
                MemoryStream ms = new MemoryStream();
                bitmap.Save(ms, ImageFormat.Jpeg);
                byte[] buffer = ms.ToArray();
                ms.Close();
                return buffer;
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }

        }



    }
}